package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHDYNUtil
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.regex.Matcher
import java.util.regex.Pattern
import java.util.stream.Collectors

// 处理动态页面语言 mode=view 仅做返回 mode=deal 操作数据库
public class apiDYNI18nDeal implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiDYNI18nDeal.class);
    private static String log_Prefix = "处理动态页面语言-";

    // 提取信息标识
    private static String[] label_Keys = "label;n;tooltip;placeholder;res".split(";");
    private static String[] compo_Keys = "com;rel".split(";");
    private static String[] skip_Keys = "binds".split(";");
    private static String[] add_Tooltip_Keys = "label".split(";");
    private static String[] js_Keys = "content".split(";");
    private static String[] js_Values = '''msg(;warn(;alert(;$F.notify(;$F.err(;$F.info(;$F.alert(;$F.warn('''.split(";");

    // 临时数据装载
    private static List<String> label_Lists = new ArrayList<>();
    private static List<String> compo_Lists = new ArrayList<>();

    // JS替换关键字
    private static List<String> js_Lists = new ArrayList<>();

    private static String no_Lang_Info = "";

    // 处理模式
    private static String staffid = "view";
    private static String deal_Mode = "view";
    private static String version = "";
    private static String dyn_Name = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        JSONObject resultJson = new JSONObject();
        resultJson.put("code", 0);
        resultJson.put("msg", "");
        resultJson.put("data", []);
        resultJson.put("data_js", []);

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            resultJson.put("code", -2);
            resultJson.put("msg", "API被非法IP调用-Request Not Allow!");
            return resultJson.toString();
        }

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        //接收客户端调用参数
        String callInfo = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callInfo += line;
        }
        log.info("[调用请求信息]:" + callInfo);

        try {
            JSONObject callJson = JSONObject.fromObject(callInfo);
            staffid = callJson.getString("staffid");
            String dynid2 = callJson.getString("dynid2");
            String mode = callJson.getString("mode");

            deal_Mode = KHUtil.isNull(mode) ? deal_Mode : mode;

            // 版本号
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String timeInfo = sdf.format(System.currentTimeMillis());
            version = "v-" + timeInfo + "-" + KHUtil.getRandomString(4).toUpperCase();
            log.debug(log_Prefix + "基础信息:staffid：" + staffid + " dynid2：" + dynid2 + " mode：" + mode);

            if (deal_Mode.equals("view") || deal_Mode.equals("deal")) {

                label_Keys = KHDBConfig.getParamConfig(eliteBean, "DYN_Lang-label_Keys").split(";");
                compo_Keys = KHDBConfig.getParamConfig(eliteBean, "DYN_Lang-compo_Keys").split(";");
                skip_Keys = KHDBConfig.getParamConfig(eliteBean, "DYN_Lang-skip_Keys").split(";");

                add_Tooltip_Keys = KHDBConfig.getParamConfig(eliteBean, "DYN_Lang-Tooltip_Keys").split(";");
                js_Keys = KHDBConfig.getParamConfig(eliteBean, "DYN_Lang-js_Keys").split(";");
                js_Values = KHDBConfig.getParamConfig(eliteBean, "DYN_Lang-js_Values").split(";");

                Map<String, Object> dyn_Label_Maps = new HashMap<String, Object>();
                Map<String, Object> dyn_js_Maps = new HashMap<String, Object>();
                Map<String, Object> dyn_jsLang_Maps = new HashMap<String, Object>();

                // 处理主页面
                label_Lists.clear();
                compo_Lists.clear();
                js_Lists.clear();
                no_Lang_Info = "";
                String re_Dyn_ID2 = doDynContent(jt, "", dynid2);
                if (label_Lists.size() > 0) {
                    dyn_Label_Maps.put(re_Dyn_ID2, JSONArray.fromObject(KHDYNUtil.doListDist(label_Lists)));
                }

                if (js_Lists.size() > 0) {
                    dyn_js_Maps.put(re_Dyn_ID2, JSONArray.fromObject(KHDYNUtil.doListDist(js_Lists)));
                    doJSLangToDB(jt, re_Dyn_ID2, KHDYNUtil.doListDist(KHDYNUtil.getzh_CNKeys(js_Lists.toString(), "([\\u4e00-\\u9fa5|0-9]+)")));
                    dyn_jsLang_Maps.put(re_Dyn_ID2, JSONArray.fromObject(KHDYNUtil.doListDist(KHDYNUtil.getzh_CNKeys(js_Lists.toString(), "([\\u4e00-\\u9fa5|0-9]+)"))));
                }
                log.debug(log_Prefix + "处理主页面结束");

                // 处理关联嵌套组件
                int loop_Num = 0;
                while (compo_Lists.size() > 0 && loop_Num < 300) {
                    loop_Num++;

                    // 将上一个动态页面语言列表清空
                    label_Lists.clear();
                    js_Lists.clear();

                    // 获取需要处理的组件ID
                    String dyn_ID = compo_Lists.get(0);
                    re_Dyn_ID2 = doDynContent(jt, dyn_ID, "");
                    if (label_Lists.size() > 0) {
                        dyn_Label_Maps.put(re_Dyn_ID2, JSONArray.fromObject(KHDYNUtil.doListDist(label_Lists)));
                    }

                    if (js_Lists.size() > 0) {
                        dyn_js_Maps.put(re_Dyn_ID2, JSONArray.fromObject(KHDYNUtil.doListDist(js_Lists)));

                        doJSLangToDB(jt, re_Dyn_ID2, KHDYNUtil.doListDist(KHDYNUtil.getzh_CNKeys(js_Lists.toString(), "([\\u4e00-\\u9fa5|0-9]+)")));

                        dyn_jsLang_Maps.put(re_Dyn_ID2, JSONArray.fromObject(KHDYNUtil.doListDist(KHDYNUtil.getzh_CNKeys(js_Lists.toString(), "([\\u4e00-\\u9fa5|0-9]+)"))));
                    }

                    compo_Lists.remove(0);
                    log.debug(log_Prefix + "处理[" + loop_Num + "]关联组件:" + dyn_ID + System.lineSeparator() + compo_Lists.toString());
                }

                resultJson.put("code", 1);
                resultJson.put("msg", "处理完成" + System.lineSeparator() + "🟢关联组件:" + loop_Num + System.lineSeparator() + "⚠️缺失清单:" + no_Lang_Info);
                resultJson.put("data", JSONArray.fromObject(dyn_Label_Maps));
                resultJson.put("data_js", JSONArray.fromObject(dyn_js_Maps));
                resultJson.put("data_jslang", JSONArray.fromObject(dyn_jsLang_Maps));

            } else if (deal_Mode.equals("deallang")) {
                doDynLangToi18n(jt, "", dynid2);

                resultJson.put("code", 1);
                resultJson.put("msg", "处理LangToi18n完成");
            } else if (deal_Mode.equals("viewlang")) {
                doDynNoLangInfo(jt, "", dynid2);

                resultJson.put("code", 1);
                resultJson.put("msg", "处理完成" + System.lineSeparator() + "⚠️缺失清单:" + no_Lang_Info);

            } else {
                resultJson.put("code", -1);
                resultJson.put("msg", "处理类型不合法:mode=view 仅做返回 mode=deal 操作数据库 mode=deallang 更新语音映射到i18n mode=viewlang 检查缺失语言");

            }

        } catch (Exception e) {
            log.error(log_Prefix + "接口处理异常", e);
            resultJson.put("code", -1);
            resultJson.put("msg", "接口处理异常" + e.getMessage());

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "处理动态页面语言[内部]", "apiDYNI18nDeal", callInfo, resultJson.toString(), (System.currentTimeMillis() - startTime).toString(), getMethod);
        }

        return resultJson.toString();
    }

    // 1-分析动态页面Dyn
    public static String doDynContent(JdbcTemplate jt, String in_dynid, String in_dynid2) {
        String Dynid = "";
        String Dynid2 = "";
        // 查询页面信息
        String dyn_ID = KHUtil.isNull(in_dynid) ? in_dynid2 : in_dynid;
        String selectSQL = KHUtil.isNull(in_dynid) ? "Select Dynid, Dynid2, Content, Dynname From Tab_Dyn Where Dynid2 = ?" : "Select Dynid, Dynid2, Content From Tab_Dyn Where Dynid = ?";
        List<Map<String, Object>> selectResult = jt.queryForList(selectSQL, dyn_ID);
        log.debug(log_Prefix + "1-分析动态页面Dyn " + "查询Dyn信息 Result:" + selectResult.toString());

        for (int i = 0; i < selectResult.size(); i++) {
            Dynid = selectResult.get(i).get("Dynid").toString();
            Dynid2 = selectResult.get(i).get("Dynid2").toString();
            String Dynname = selectResult.get(i).get("Dynname").toString();
            String Content = selectResult.get(i).get("Content").toString();
            log.debug(log_Prefix + "基础Dyn信息:Dynid：" + Dynid + " Dynid2：" + Dynid2 + " Content：" + Content + " Dynname：" + Dynname);

            dyn_Name = !KHUtil.isNull(in_dynid2) ? Dynname : dyn_Name;

            String NContent = analysisDyn(Content);
            log.debug(log_Prefix + "1-分析动态页面Dyn " + "处理Dyn后 Content：" + NContent);

            if (deal_Mode == "deal") {
                String updateSQL = '''Insert Into Tab_Dyn_Publish
                                          (Guid,
                                           Dynid,
                                           Dynid2,
                                           Dynname,
                                           Stateful,
                                           Trackablity,
                                           Theme,
                                           Content,
                                           Wunit,
                                           Hunit,
                                           Version,
                                           Archetype,
                                           Publishedtime)
                                          Select Uuid(),
                                                 Dynid,
                                                 Dynid2,
                                                 Dynname,
                                                 Stateful,
                                                 Trackablity,
                                                 Theme,
                                                 Content,
                                                 Wunit,
                                                 Hunit,
                                                 ?,
                                                 Date_Format(Now(), '%Y%m%d%H%i%s'),
                                                 Now()
                                            From Tab_Dyn
                                           Where Dynid = ?''';
                int updateNum = jt.update(updateSQL, version, Dynid);
                log.debug(log_Prefix + "1-分析动态页面Dyn " + "备份Dyn数据到Tab_Dyn_Publish：" + updateNum);

                updateSQL = '''Update Tab_Dyn Set Content = ?, Modifiedby = ?, Modifiedtime = Now() Where Dynid = ?''';
                updateNum = jt.update(updateSQL, NContent, staffid, Dynid);
                log.debug(log_Prefix + "1-分析动态页面Dyn " + "更新Dyn数据到Tab_Dyn：" + updateNum);
            }

            doDynPageContent(jt, Dynid);
        }
        log.debug(log_Prefix + "1-分析动态页面Dyn " + "#解析处理完成:Dynid2：" + Dynid2 + " 语言参数：" + label_Lists.toString());

        // 将页面数据写入语言表
        doDynLangToDB(jt, Dynid2);

        // 将动态页面语言结果动态页面语言表
        if (deal_Mode == "deal") {
            doDynLangToi18n(jt, Dynid, Dynid2);
        }

        // 检测缺失翻译
        doDynNoLangInfo(jt, Dynid, Dynid2);

        return Dynid2;

    }

    // 2-分析动态页面DynPage
    public static void doDynPageContent(JdbcTemplate jt, String in_dynid) {

        // 查询页面信息
        String dyn_ID = in_dynid;
        String selectSQL = "Select Dynid, Pageid, Content From Tab_Dyn_Page Where Dynid = ?";
        List<Map<String, Object>> selectResult = jt.queryForList(selectSQL, dyn_ID);
        log.debug(log_Prefix + "2-分析动态页面DynPage " + "查询DynPage信息 Result:" + selectResult.toString());

        for (int i = 0; i < selectResult.size(); i++) {
            String Dynid = selectResult.get(i).get("Dynid").toString();
            String Pageid = selectResult.get(i).get("Pageid").toString();
            String Content = selectResult.get(i).get("Content").toString();
            log.debug(log_Prefix + "2-分析动态页面DynPage " + "基础DynPage信息:Dynid：" + Dynid + " Pageid：" + Pageid + " Content：" + Content);
            String NContent = analysisDyn(Content);
            log.debug(log_Prefix + "2-分析动态页面DynPage " + "处理DynPage后 Content：" + NContent);

            if (deal_Mode == "deal") {
                String updateSQL = '''Insert Into Tab_Dyn_Page_Publish
                                      (Guid, Dynid, Pageid, Version, Content)
                                      Select Uuid(), Dynid, Pageid, ?, Content From Tab_Dyn_Page Where Dynid = ? And Pageid = ?''';
                int updateNum = jt.update(updateSQL, version, Dynid, Pageid);
                log.debug(log_Prefix + "2-分析动态页面DynPage " + "备份DynPage数据到Tab_Dyn_Page_Publish：" + updateNum);

                updateSQL = '''Update Tab_Dyn_Page Set Content = ? Where Dynid = ? And Pageid = ?''';
                updateNum = jt.update(updateSQL, NContent, Dynid, Pageid);
                log.debug(log_Prefix + "2-分析动态页面DynPage " + "更新DynPage数据到Tab_Dyn_Page：" + updateNum);
            }
        }

    }

    // 3-将动态页面语言结果写入表
    public static void doDynLangToDB(JdbcTemplate jt, String in_Dyn_ID2) {

        // 将字段写入语言表
        for (int i = 0; i < label_Lists.size(); i++) {
            String I18n_Key = label_Lists.get(i);
            // 查询任务对应的Kafka、Topic配置信息
            String selectSQL = '''Select Rec_Guid, Dyn_Id
                                      From Hst_I18n
                                     Where Dyn_Id = ?
                                       And I18n_Type = 'en_US'
                                       And I18n_Key = ?''';

            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, in_Dyn_ID2, I18n_Key);
            if (selectExits.size() == 0) {
                String updateSQL = '''Insert Into Hst_I18n
                                      (Rec_Guid, Dyn_Id, Dyn_Name, I18n_Type, I18n_Key, I18n_Value, Createdby, Createddate, ModifiedBy, ModifiedDate)
                                      Select Uuid(), Dynid2, Dynname, 'en_US', ?, '', ?, Now(), ?, Now() From Tab_Dyn Where Dynid2 = ?''';
                int updateNum = jt.update(updateSQL, I18n_Key, staffid, staffid, in_Dyn_ID2);
                log.debug(log_Prefix + "3-将动态页面语言结果写入表 " + "将动态页面语言结果写入表:Dynid2：" + in_Dyn_ID2 + " 语言Key：" + I18n_Key + " Result:" + updateNum);
            } else {
                String updateSQL = '''Update Hst_I18n
                                       Set Modifiedby = ?, Modifieddate = Now()
                                     Where I18n_Type = 'en_US'
                                       And Dyn_Id = ?
                                       And I18n_Key = ?''';
                int updateNum = jt.update(updateSQL, staffid, in_Dyn_ID2, I18n_Key);
                log.debug(log_Prefix + "3-将动态页面语言结果写入表 " + "将动态页面语言结果更新表:Dynid2：" + in_Dyn_ID2 + " 语言Key：" + I18n_Key + " Result:" + updateNum);

            }
        }
        log.debug(log_Prefix + "3-将动态页面语言结果写入表 " + "将动态页面语言结果写入表完成..");

    }

    // 4-将动态页面语言结果动态页面语言表
    public static void doDynLangToi18n(JdbcTemplate jt, String in_Dyn_ID, String in_Dyn_ID2) {

        // 将字段写入语言表
        String selectSQL = '''Select R2.Dynid,
                                   R2.Dynid2,
                                   R2.Dynname,
                                   Case
                                     When R2.Dyntype = 1 Then
                                      '组件'
                                     Else
                                      '页面'
                                   End As Dyntype,
                                   R1.I18n_Type,
                                   R1.I18n_Key,
                                   Case
                                     When R1.I18n_Value Is Null Or R1.I18n_Value = '' Then
                                      R3.I18n_Value
                                     Else
                                      R1.I18n_Value
                                   End As I18n_Value
                              From Hst_I18n R1
                              Left Join Tab_Dyn R2
                                On R1.Dyn_Id = R2.Dynid2
                              Left Join (Select R1.Rec_Guid, R1.I18n_Key, R1.I18n_Value
                                           From Hst_I18n_Excel R1
                                           Left Join (Select I18n_Key, Min(Rec_Guid) As Rec_Guid From Hst_I18n_Excel R1 Group By I18n_Key) R2
                                             On R1.Rec_Guid = R2.Rec_Guid
                                          Where R2.Rec_Guid Is Not Null) R3
                                On R1.I18n_Key = R3.I18n_Key
                             Where Case
                                     When R1.I18n_Value Is Null Or R1.I18n_Value = '' Then
                                      R3.I18n_Value
                                     Else
                                      R1.I18n_Value
                                   End Is Not Null
                               And Case
                                     When R1.I18n_Value Is Null Or R1.I18n_Value = '' Then
                                      R3.I18n_Value
                                     Else
                                      R1.I18n_Value
                                   End != ''
                               And R1.Dyn_Id = ?
                             Order By R2.Dyntype, R2.Dynid, R1.I18n_Type, R1.I18n_Key''';

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, in_Dyn_ID2);
        log.debug(log_Prefix + "4-将动态页面语言结果动态页面语言表 " + "*动态页面语言表" + selectExits.toString());

        if (selectExits.size() > 0) {
            in_Dyn_ID = KHUtil.isNull(in_Dyn_ID) ? selectExits.get(0).get("Dynid").toString() : in_Dyn_ID;
            JSONObject contentJson = new JSONObject();
            for (int i = 0; i < selectExits.size(); i++) {
                String I18n_Key = selectExits.get(i).get("I18n_Key").toString();
                String I18n_Value = selectExits.get(i).get("I18n_Value").toString();
                contentJson.put(I18n_Key, I18n_Value);
            }
            log.debug(log_Prefix + "4-将动态页面语言结果动态页面语言表 " + "动态页面语言表:in_Dyn_ID：" + in_Dyn_ID + "动态页面语言表:in_Dyn_ID2：" + in_Dyn_ID2 + " 语言json：" + contentJson.toString());

            String updateSQL = '''Insert Into Tab_Dyn_I18n_Publish
                                  (Guid, Dynid, Lang, Version, Content)
                                  Select uuid(), Dynid, Lang, ?, Content
                                    From Tab_Dyn_I18n
                                   Where Dynid = ?''';
            int updateNum = jt.update(updateSQL, version, in_Dyn_ID);
            log.debug(log_Prefix + "4-将动态页面语言结果动态页面语言表 " + "将动态页面语言结果写入表Tab_Dyn_I18n_Publish:" + updateNum);

            updateSQL = '''Delete From Tab_Dyn_I18n Where Dynid = ?''';
            updateNum = jt.update(updateSQL, in_Dyn_ID);
            log.debug(log_Prefix + "4-将动态页面语言结果动态页面语言表 " + "将动态页面语言表Tab_Dyn_I18n Delete:" + updateNum);

            updateSQL = '''Insert Into Tab_Dyn_I18n (Dynid, Lang, Content) Values (?, 'en_US', ?)''';
            updateNum = jt.update(updateSQL, in_Dyn_ID, contentJson.toString());
            log.debug(log_Prefix + "将动态页面语言结果写入表Tab_Dyn_I18n:Dynid：" + in_Dyn_ID + " 语言JSONObject：" + contentJson.toString() + " Result:" + updateNum);
        } else {

            log.debug(log_Prefix + "4-将动态页面语言结果动态页面语言表 " + "将动态页面语言结果动态页面语言表..");
        }

    }

    // 5-获取动态页面缺失翻译
    public static void doDynNoLangInfo(JdbcTemplate jt, String in_Dyn_ID, String in_Dyn_ID2) {

        // 将字段写入语言表
        String selectSQL = '''Select R2.Dynid,
                                   R2.Dynid2,
                                   R2.Dynname,
                                   Case
                                     When R2.Dyntype = 1 Then
                                      '组件'
                                     Else
                                      '页面'
                                   End As Dyntype,
                                   R1.I18n_Type,
                                   R1.I18n_Key,
                                   Case
                                     When R1.I18n_Value Is Null Or R1.I18n_Value = '' Then
                                      R3.I18n_Value
                                     Else
                                      R1.I18n_Value
                                   End As I18n_Value
                              From Hst_I18n R1
                              Left Join Tab_Dyn R2
                                On R1.Dyn_Id = R2.Dynid2
                              Left Join (Select R1.Rec_Guid, R1.I18n_Key, R1.I18n_Value
                                           From Hst_I18n_Excel R1
                                           Left Join (Select I18n_Key, Min(Rec_Guid) As Rec_Guid From Hst_I18n_Excel R1 Group By I18n_Key) R2
                                             On R1.Rec_Guid = R2.Rec_Guid
                                          Where R2.Rec_Guid Is Not Null) R3
                                On R1.I18n_Key = R3.I18n_Key
                             Where (Case
                                     When R1.I18n_Value Is Null Or R1.I18n_Value = '' Then
                                      R3.I18n_Value
                                     Else
                                      R1.I18n_Value
                                   End Is Null
                               Or Case
                                     When R1.I18n_Value Is Null Or R1.I18n_Value = '' Then
                                      R3.I18n_Value
                                     Else
                                      R1.I18n_Value
                                   End = '')
                               And R1.Dyn_Id = ?
                             Order By R2.Dyntype, R2.Dynid, R1.I18n_Type, R1.I18n_Key''';

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, in_Dyn_ID2);
        log.debug(log_Prefix + "5-获取动态页面缺失翻译 " + "*缺失翻译查询结果:" + selectExits.toString());

        List<String> no_langs = new ArrayList<>();
        String Dynid2 = "";
        String Dynname = "";
        String Dyntype = "";
        String I18n_Key = "";
        for (int i = 0; i < selectExits.size(); i++) {
            Dynid2 = selectExits.get(i).get("Dynid2").toString();
            Dynname = selectExits.get(i).get("Dynname").toString();
            Dyntype = selectExits.get(i).get("Dyntype").toString();
            I18n_Key = selectExits.get(i).get("I18n_Key").toString();
            no_langs.add(I18n_Key);
        }

        if (no_langs.size() > 0) {
            no_Lang_Info = no_Lang_Info + System.lineSeparator() + "🔸" + Dyntype + ":" + Dynid2 + " 【" + Dynname + "】" + System.lineSeparator() + no_langs.toString();
        }

    }

    // 6-将动态页面JS语言结果写入表
    public static void doJSLangToDB(JdbcTemplate jt, String in_Dyn_ID2, List<String> jsLang_Lists) {

        // 将字段写入语言表
        for (int i = 0; i < jsLang_Lists.size(); i++) {
            String I18n_Key = jsLang_Lists.get(i);
            // 查询任务对应的Kafka、Topic配置信息
            String selectSQL = '''Select Rec_Guid, Dyn_Id
                                      From Hst_I18n
                                     Where Dyn_Id = ?
                                       And I18n_Type = 'en_US'
                                       And I18n_Key = ?''';

            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, in_Dyn_ID2, I18n_Key);
            if (selectExits.size() == 0) {
                String updateSQL = '''Insert Into Hst_I18n
                                      (Rec_Guid, Dyn_Id, Dyn_Name, I18n_Type, I18n_Key, I18n_Value, Createdby, Createddate, ModifiedBy, ModifiedDate)
                                      Select Uuid(), Dynid2, Concat(Dynname, '#JS'), 'en_US', ?, '', ?, Now(), ?, Now() From Tab_Dyn Where Dynid2 = ?''';
                int updateNum = jt.update(updateSQL, I18n_Key, staffid, staffid, in_Dyn_ID2);
                log.debug(log_Prefix + "6-将动态页面JS语言结果写入表 " + "将动态页面JS语言结果写入表:Dynid2：" + in_Dyn_ID2 + " 语言Key：" + I18n_Key + " Result:" + updateNum);
            } else {
                String updateSQL = '''Update Hst_I18n
                                       Set Modifiedby = ?, Modifieddate = Now()
                                     Where I18n_Type = 'en_US'
                                       And Dyn_Id = ?
                                       And I18n_Key = ?''';
                int updateNum = jt.update(updateSQL, staffid, in_Dyn_ID2, I18n_Key);
                log.debug(log_Prefix + "6-将动态页面JS语言结果写入表 " + "将动态页面JS语言结果更新表:Dynid2：" + in_Dyn_ID2 + " 语言Key：" + I18n_Key + " Result:" + updateNum);

            }
        }
        log.debug(log_Prefix + "6-将动态页面JS语言结果写入表 " + "将动态页面JS语言结果写入表完成..");

    }

    public static String analysisDyn(String str) {
        // log.debug(log_Prefix + "analysisDyn-Json：" + str);
        JSONObject json = null;
        JSONObject re_Json = null;
        json = JSONObject.fromObject(str);
        re_Json = JSONObject.fromObject(str);
        Set<String> keySet = json.keySet();
        for (String key : keySet) {
            if (!Arrays.asList(skip_Keys).contains(key)) {
                Object obj = json.get(key);
                if (obj instanceof JSONArray) {
                    JSONArray arr = (JSONArray) obj;
                    for (int i = 0; i < arr.size(); i++) {
                        if (arr.get(i) instanceof JSONObject) {
                            String child = analysisDyn(arr.get(i).toString());
                            arr.set(i, JSONObject.fromObject(child));
                        } else {
                            log.debug(log_Prefix + "analysisDyn-Json#：" + arr.get(i).toString());
                            arr.set(i, arr.get(i).toString());
                        }
                    }
                    re_Json.put(key, arr);
                } else if (obj instanceof JSONObject) {
                    JSONObject sub = (JSONObject) obj;
                    String substr = analysisDyn(sub.toString());
                    re_Json.put(key, JSONObject.fromObject(substr));
                } else {
                    boolean is_Tooltip = json.has("tooltip");
                    String key_Value = obj.toString().trim();
                    if (Arrays.asList(label_Keys).contains(key)) {

                        log.debug(log_Prefix + "#解析后原始信息-key：" + key + " value：" + key_Value);
                        // key_Value = key_Value.replaceAll("!", ".").replaceAll("！", ".").replaceAll("，", ".").replaceAll(",", ".").replaceAll("\\(", "_").replaceAll("（", "_").replaceAll("\\)", ".").replaceAll("）", ".");
                        // log.debug(log_Prefix + "#替换特殊标点后原始信息-key：" + key + " value：" + key_Value);

                        // 判断是否已经替换
                        if (!KHUtil.isNull(key_Value) && KHDYNUtil.isContainChinese(key_Value)) {

                            // 1-处理标签中有i class
                            try {
                                log.debug(log_Prefix + "#语言数据-key：" + key + " value：" + key_Value);
                                List<String> key_CNLists = KHDYNUtil.getzh_CNKeys(key_Value, "([\\u4e00-\\u9fa5|0-9]+)");
                                key_Value = KHDYNUtil.doReplCNData2(key_Value);
                                re_Json.put(key, key_Value);

                                label_Lists.addAll(key_CNLists);

                                if (!is_Tooltip && Arrays.asList(add_Tooltip_Keys).contains(key)) {
                                    re_Json.put("tooltip", key_Value);
                                }

                            } catch (Exception e) {
                                log.debug(log_Prefix + "#语言数据-key：" + key + " value：" + key_Value + " 异常-" + e.getMessage());

                            }
                        } else {
                            // 语言字段为空或未包含中文
                            log.debug(log_Prefix + "#语言数据-key：" + key + " value：" + key_Value + " 语言字段为空或未包含中文");
                        }
                    } else if (Arrays.asList(js_Keys).contains(key)) {

                        log.debug(log_Prefix + "#JS代码数据-key：" + key + " value：" + key_Value + " 原始");
                        key_Value = doJSLine(key_Value);
                        re_Json.put(key, key_Value);
                        log.debug(log_Prefix + "#JS代码数据-key：" + key + " value：" + key_Value + " 替换后");
                    } else {
                        if (Arrays.asList(compo_Keys).contains(key) && key_Value.length() >= 36) {
                            log.debug(log_Prefix + "*关联标签-key：" + key + " value：" + key_Value);
                            compo_Lists.add(key_Value);
                        }
                    }
                }
            } else {
                log.debug(log_Prefix + "Json数据-key：" + key + " Key跳过");

            }
        }
        return re_Json.toString();
    }

    public static String doJSLine(String s) {
        String strbuf = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                for (String str : js_Values) {
                    if (line.indexOf(str) >= 0) {

                        line = KHDYNUtil.doReplCNData2(line);
                        js_Lists.add(line.trim());
                    }

                }
                strbuf = strbuf + line + "\n";
                log.debug(log_Prefix + "原始行数据处理后###:" + strbuf);
            }
        } catch (Exception e) {
            log.error("doJSLine 异常", e);
        }
        return strbuf;
    }

}
